17. Overloading Functions

Overloading

Now that we’ve seen how to create a class and talked about some of the fundamental functions and variables that classes contain, let’s look at something new!

The double underscore __X__

You’ve seen a couple of examples of functions that have a double underscore, like:

 __init__

__repr__

These are special functions that are used by Python in a specific way.

We typically don't call these functions directly, as we do with ones like move() and `turn_left().

Instead, Python calls them automatically based on our use of keywords and operators.

For example, __init__ is called when we create a new object and __repr__ is called when we tell Python to print the string representation of a specific object!

Another example: __add__

All of these special functions have their names written between double underscores __, and there are many of these types of functions! To see the full list of these functions, check out the Python documentation.

For example, we can define what happens when we add two car objects together using a + symbol by defining the __add__ function.

def __add__(self, other):
    # Create an empty list
    added_state = []

    # Add the states together, element-wise
    for i in range(self.state):
        added_value = self.state[i] + other.state[i]
        added_state.append(added_value)

    return added_state

The above version, adds together the state variables! Or.. you may choose to just print out that adding cars is an invalid operation, as below.

def __add__(self, other):
    # Print an error message and return the unchanged, first state
    print('Adding two cars is an invalid operation!')
    return self.state

Operator Overloading

When we define these functions in our class, this is called operator overloading.

And, in this case, overloading just means: giving more than one meaning to a standard operator like addition.

Operator overloading can be a powerful tool, and you’ll not only see it pop up again and again in classes, but it is useful for writing classes that are intuitive and simple to use. So, keep this in mind as you continue learning, and let's get some practice with overloading operators!